package com.sjme.filter;

import com.sjme.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.constant.CommonConstant.URL.LOGIN_URL;
import static com.constant.RedisKey.User.INTERVIEW_PC_LOGIN_TOKEN;

@Slf4j
@Component
public class InterviewGlobalFilter implements GlobalFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AESUtil aesUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求路径
        String path = exchange.getRequest().getURI().getPath();
        // 若是登陆请求，则直接放行
        if (StringUtils.pathEquals(path, LOGIN_URL)) {
            return chain.filter(exchange);
        }
        // 获取请求头信息
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst("Authorization");
        if (StringUtils.isEmpty(token)) {
            log.error("请求路径 {} 缺少Token", path);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 校验token是否有效
        String userId = aesUtil.decrypt(token);
        String cacheKey = INTERVIEW_PC_LOGIN_TOKEN + userId;
        String cacheToken = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isEmpty(cacheToken)) {
            log.error("请求路径 {} Token已过期", path);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if (!cacheToken.equals(token)) {
            log.error("请求路径 {} Token无效", path);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 重建请求，并将userId设置到请求头
        ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.add("userId", userId + "");
        }).build();
        //重置header
        exchange.mutate().request(serverHttpRequest).build();
        // 放行
        return chain.filter(exchange);
    }

}
